<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                  <el-form-item label="名称" prop="name">
                    <el-input
                        v-model="queryParams.name"
                        placeholder="请输入名称"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                  </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['exec:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['exec:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['exec:template:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    
    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="id" align="center" prop="id" />
              <el-table-column label="名称" align="center" prop="name" />
              <el-table-column label="命令" align="center" prop="command" />
              <el-table-column label="超时时间秒" align="center" prop="timeout"/>
              <!-- <el-table-column label="是否使用脚本执行" align="center" prop="scriptExec" /> -->
              <el-table-column label="参数定义" align="center" prop="parameterSchema" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['exec:template:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['exec:template:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改执行模板对话框 -->
       <el-drawer
    v-model="open"
    :title="title"
    :before-close="handleClose"
    direction="rtl"
 size="70%"
  :with-footer="false"
  :modal-append-to-body="true"
  :modal="true"
  :lock-scroll="true"
  :show-close="true"
 :with-header="true"
 :close-on-press-escape="true"
  :destroy-on-close="true"
 @close="cancel"
  >
    <el-form ref="templateRef" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="名称" prop="name">
      <el-input v-model="form.name" placeholder="请输入名称" />
    </el-form-item>
    <el-form-item label="命令" prop="command">
      <el-input
        v-model="form.command"
        type="textarea"
        :rows="8"
        placeholder="请输入shell命令"
        class="shell-input"
      />
    </el-form-item>
    <el-form-item label="超时时间" prop="timeout">
      <el-input v-model="form.timeout" placeholder="请输入超时时间秒 0不超时"  model-value="0"/>
    </el-form-item>
        <!-- 参数定义部分 -->
        <el-form-item label="参数定义">
          <div >
            <span style="color: #999; font-size: 12px; display: block; margin-bottom: 8px;">
              使用 @{Xxx} 来替换参数，输入_可以获取全部变量
            </span>
            <el-button
              type="primary"
              icon="Plus"
              @click="addParam"
              plain
            >添加参数</el-button>
          
          <!-- 参数列表 -->
          <div
            v-for="(param, idx) in paramList"
            :key="idx"
            class="param-row"
            style="display: flex; align-items: flex-start; margin-bottom: 12px;"
          >
      <span class="param-label" style="margin-right: 12px; margin-top: 10px;">参数名:</span>
    <el-input v-model="param.key" placeholder="参数名" style="width: 286px; margin-right: 12px; margin-top: 10px;" />
    <span class="param-label" style=" margin-right: 12px;margin-top: 10px;">参数值:</span>
    <el-input v-model="param.value" placeholder="参数值" style="width: 286px; margin-right: 12px;margin-top: 10px;" />
    <span class="param-label" style=" margin-right: 12px;margin-top: 10px;">参数描述:</span>
    <el-input v-model="param.desc" placeholder="参数描述" style="width: 286px; margin-right: 12px;margin-top: 10px;" />
            <el-button
      type="danger"
      icon="Delete"
      @click="removeParam(idx)"
      circle
    />
          </div>
          </div>
        </el-form-item>
        <div class="dialog-footer" style="text-align:right;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>


<script setup name="Template">
  import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/exec/template"

  const { proxy } = getCurrentInstance()

  const templateList = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")
const paramList = ref([]); // 参数数组
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
                    name: null,
                    command: null,
                    timeout: null,
                    scriptExec: null,
                    parameterSchema: null,
    },
    rules: {
    }
  })

  const { queryParams, form, rules } = toRefs(data)

  /** 查询执行模板列表 */
  function getList() {
    loading.value = true
    listTemplate(queryParams.value).then(response => {
            templateList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }
  
  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
                    id: null,
                    name: null,
                    command: null,
                    timeout: null,
                    scriptExec: null,
                    parameterSchema: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null
    }
    proxy.resetForm("templateRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    paramList.value = []; // 重置参数列表
    open.value = true
    title.value = "添加执行模板"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
 reset()
  const _id = row.id || ids.value
  getTemplate(_id).then(response => {
    form.value = response.data
    // 回显参数
    try {
      paramList.value = form.value.parameterSchema ? JSON.parse(form.value.parameterSchema) : null;
    } catch {
      paramList.value = [];
    }
    open.value = true
    title.value = "修改执行模板"
  })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["templateRef"].validate(valid => {
      if (valid) {
          form.value.parameterSchema = paramList.value.length > 0 
        ? JSON.stringify(paramList.value) 
        : null;
        if (form.value.id != null) {
          updateTemplate(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          addTemplate(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal.confirm('是否确认删除执行模板编号为"' + _ids + '"的数据项？').then(function() {
      return delTemplate(_ids)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  }

function addParam() {
  paramList.value.push({ key: '', value: '', desc: '' });
}
function removeParam(index) {
  paramList.value.splice(index, 1);
}

  getList()
</script>
<style>
.shell-input textarea {
  background: #222;
  color: #fff;
  font-family: "Fira Mono", "Consolas", "Menlo", monospace;
  font-size: 14px;
  border-radius: 4px;
    height: 703px;
}
.param-row {
  display: flex;
   align-items: flex-start;
  margin-bottom: 8px;
}
  .param-header {
    padding: 0 8px;
    color: #606266;
    font-size: 14px;
  }
</style>
